// 登录和注册的store
import { reqGetCode, reqUserRegist ,reqUserLogin,reqUserInfo,reqLogout} from "@/api";
import {setToken,getToken,clearToken} from "@/utils/token"

const state = {
  code: "",
  // 登录过后，在刷新页面，从localStorage里面拿
  token:getToken(),
  userInfo:{}
};

const mutations = {
  GETCODE(state, code) {
    state.code = code;
  },
  USERTOKEN(state, token) {
    state.token = token;
  },
  GETUSERINFO(state, userInfo) {
    state.userInfo = userInfo;
  },
  // 清除本地数据
  CLEAR(){
    state.token='',
    state.userInfo={},
    clearToken();
  }
};

const actions = {
  // 获取验证码
  async getCode({ commit }, phone) {
    let res = await reqGetCode(phone);
    if (res.code == 200) {
      commit("GETCODE", res.data);
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  //   注册
  async userRegister({ commit }, userInfo) {
    let res = await reqUserRegist(userInfo);
    // console.log(res);
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("faile"));
    }
  },
  //   登录
  async userLogin({ commit }, userInfo) {
    let res = await reqUserLogin(userInfo);
    // console.log(res);
    if(res.code==200){
      // 已经获取到token
      commit("USERTOKEN",res.data.token)
      // 持久化token
      setToken(res.data.token)
    }
  },
  //   获取用户信息
  async getUserInfo({ commit }) {
    let res = await reqUserInfo();
    // console.log(res);
    if(res.code==200){
      commit("GETUSERINFO",res.data)
      return 'ok'
    }else{
      return Promise.reject(new Error('faile'))
    }
  },

  async userLogout({ commit }){
     let res= await reqLogout();
     console.log(res)
     if(res.code==200){
       commit("CLEAR")
       return "ok"
     }else{
       return Promise.reject(new Error('faile'))
     }
  },
};
const getters = {};

export default { state, mutations, actions, getters };

